<template>
  <div class="permission-assign-container">
    <el-select 
      v-model="selectedAccount" 
      placeholder="账号选择"
    >
      <el-option
        v-for="account in permissionStore.filteredUsers"
        :key="account.id"
        :label="account.username"
        :value="account.id"
      />
    </el-select>
    <el-table 
      v-loading="permissionStore.loading"
      element-loading-text="加载中..."
      :data="permissionStore.menuList" 
      style="width: 100%"
    >
      <el-table-column prop="index" label="序号" width="80">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="selfid" label="菜单id" width="120" />
      <el-table-column prop="name" label="菜单名称" />
      <el-table-column label="权限状态" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.flag"
            :active-value="1"
            :inactive-value="0"
            @change="handleRightChange(scope.row.selfid, scope.row.flag === 1)"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { usePermissionStore } from '@/stores/permission'
import type { MenuItem } from '@/api/types/permission'

const permissionStore = usePermissionStore()
const selectedAccount = ref<number>()

const handleRightChange = async (menuId: number, enabled: boolean) => {
  const success = await permissionStore.updateMenuRight(menuId, enabled)
  if (!success) {
    await permissionStore.fetchMenuList(selectedAccount.value)
  }
}

const initializeData = async () => {
  await permissionStore.fetchSystemUsers()
  
  if (permissionStore.filteredUsers.length > 0) {
    const firstUser = permissionStore.filteredUsers[0]
    selectedAccount.value = firstUser.id
    permissionStore.selectedUsername = firstUser.username
    await permissionStore.fetchMenuList(firstUser.id)
  }
}

onMounted(() => {
  initializeData()
})

watch(selectedAccount, async (newValue) => {
  if (newValue) {
    const selectedUser = permissionStore.filteredUsers.find(user => user.id === newValue)
    if (selectedUser) {
      permissionStore.selectedUsername = selectedUser.username
      await permissionStore.fetchMenuList(newValue)
    }
  }
})
</script>

<style lang="scss" scoped>
.permission-assign-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.el-select {
  margin-bottom: 20px;
  width: 200px;
}
</style>